package com.junjiao.util.mobile;

import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.awt.image.BufferedImage;

import javax.imageio.ImageIO;

import com.google.zxing.BinaryBitmap;
import com.google.zxing.DecodeHintType;
import com.google.zxing.LuminanceSource;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.Result;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;

/**
 * @description: 二维码、条形码工具类 zxing 2.2<br>
 * @author:jiaojun
 * @email:junjiao.j@gmail.com
 * @project:junjiao util
 * @version:v0.2
 * @date:2013-7-6
 */
public class ZxingUtil {

	/**
	 * 
	 * @description: 二维码编码 <br>
	 * @author:jiaojun
	 * @param contents
	 *            欲编码内容
	 * @param width
	 *            生成二维码图片宽度
	 * @param height
	 *            生成二维码图片高度
	 * @param imgPath
	 *            生成二维码图片路径
	 */
	public static void encode(String contents, int width, int height, String imgPath) {
		long start = System.currentTimeMillis();
		Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>();
		/**
		 * 容错率共四档:
			L     7%
			M    15%
			Q     25%
			H     30%
		 */
		hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
		/**
		 * 指定编码格式:特别声明此处的编码使用小写如utf-8 gbk
		 * 使用“UTF-8”，会在文本编码前添加一段ECI(扩充解释Extended Channel Interpretation)编码，就是这段编码导致手机不能解析。
		 * 如果使用小写"utf-8"会使这个ECI判断失效而不影响内容编码方式。
		 * 至于详细的ECI解释，可以看《QRCode 编码解码标准》
		 */
		hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
		// 指定空白边框大小
		hints.put(EncodeHintType.MARGIN, 1); 
		try {
			BitMatrix bitMatrix = new MultiFormatWriter().encode(new String(contents.getBytes("GBK")), BarcodeFormat.QR_CODE, width, height, hints);

			MatrixToImageWriter.writeToFile(bitMatrix, "png", new File(imgPath));
			System.out.println(System.currentTimeMillis()-start);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * @description: 二维码解码 <br>
	 * @author:jiaojun
	 * @param imgPath
	 *            二维码图片地址
	 * @return 解码内容
	 */
	public static String decode(String imgPath) {
		BufferedImage image = null;
		Result result = null;
		try {
			image = ImageIO.read(new File(imgPath));
			if (image == null) {
				System.out.println("the decode image may be not exit.");
			}
			LuminanceSource source = new BufferedImageLuminanceSource(image);
			BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));

			Map<DecodeHintType, Object> hints = new HashMap<DecodeHintType, Object>();
			hints.put(DecodeHintType.CHARACTER_SET, "GBK");

			result = new MultiFormatReader().decode(bitmap, hints);
			return result.getText();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * @description: 条形码编码 <br>
	 * @author:jiaojun
	 * @param contents
	 *            欲编码内容
	 * @param width
	 *            生成二维码图片宽度
	 * @param height
	 *            生成二维码图片高度
	 * @param imgPath
	 *            生成二维码图片路径
	 */
	public static void encodeEAN13(String contents, int width, int height, String imgPath) {
		int codeWidth = 3 + // start guard
				(7 * 6) + // left bars
				5 + // middle guard
				(7 * 6) + // right bars
				3; // end guard
		codeWidth = Math.max(codeWidth, width);
		try {
			BitMatrix bitMatrix = new MultiFormatWriter().encode(contents, BarcodeFormat.EAN_13, codeWidth, height, null);

			MatrixToImageWriter.writeToFile(bitMatrix, "png", new File(imgPath));

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * @description: 条形码解码 <br>
	 * @author:jiaojun
	 * @param imgPath
	 *            二维码图片地址
	 * @return 解码内容
	 */
	public static String decodeEAN13(String imgPath) {
		BufferedImage image = null;
		Result result = null;
		try {
			image = ImageIO.read(new File(imgPath));
			if (image == null) {
				System.out.println("the decode image may be not exit.");
			}
			LuminanceSource source = new BufferedImageLuminanceSource(image);
			BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));

			result = new MultiFormatReader().decode(bitmap, null);
			return result.getText();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public static void main(String[] args) {
		 String imgPath = "d:/test_zxing3.png";
		 String contents = "welcome to http://blog.csdn.net/sl0007";
		 int width = 300, height = 300;
		 encode(contents, width, height, imgPath);
		 System.out.println("zxing encode end");
		
//		 String decodeContent = decode(imgPath);
//		 System.out.println("解码内容如下：");
//		 System.out.println(decodeContent);
//		 System.out.println("zxing decode end");

//		String imgPath = "d:/test_EAN13.png";
//		String contents = "6936411400037";
//		int width = 105, height = 50;
//		encodeEAN13(contents, width, height, imgPath);
//		System.out.println("EAN13 encode end");
//
//		String decodeContent = decodeEAN13(imgPath);
//		System.out.println("解码内容如下：");
//		System.out.println(decodeContent);
//		System.out.println("EAN13 decode end");

	}
}
